package info.niwota.start;

import java.io.File;
import java.io.IOException;

import android.content.Context;
import android.net.Uri;
import android.os.Environment;

/**
 * @author qiangli
 * 
 */
public final class Files {

	public static final String SUB_IMAGE = "images";
	public static final String SUB_AUDIO =  "audio";
	
	private static final String TOP = "info.niwota.start";

	public static File getTempFile(File dir, String prefix, String ext)
			throws IOException {
		if (!dir.exists()) {
			dir.mkdirs();
		}
		return File.createTempFile(prefix, ext, dir);
	}

	private static File getSubFolder(Context ctx, String sub) {
		String path = Files.getDefaultRoot().getPath();
		File dir = new File(path, sub);
		if (!dir.exists()) {
			dir.mkdir();
		}
		return dir;
	}

	private static File getDefaultRoot() {
		File root = Environment.getExternalStorageDirectory();
		File sub = new File(root, TOP);
		return sub;
	}

	public static File toFile(String uri) {
		if (uri.startsWith("file:")) {
			Uri u = Uri.parse(uri);
			String p = u.getPath();
			return new File(p);
		}
		return new File(uri);
	}

	public static Uri toUri(String path) {
		if (path.startsWith("file:")) {
			return Uri.parse(path);
		}
		return Uri.parse("file:" + path);
	}

	public static File getImageFolder(Context ctx) {
		return getSubFolder(ctx, Files.SUB_IMAGE);
	}
}
